import { Layout } from "@/components/layout/layout";
import withAuth, { getServerSideProps } from "@/hoc/withAuth";
import { useHttp } from "@/hooks";
import useMounted from "@/hooks/useMounted";
import type { NextPage, GetServerSidePropsContext } from "next";
import Link from "next/link";
import { useRouter } from "next/router";
import { useEffect, useRef, useState } from "react";
import React from "react";
import {
  Table,
  TableHeader,
  TableColumn,
  TableBody,
  TableRow,
  TableCell,
  getKeyValue,
  Button,
  Image,
  Chip,
} from "@nextui-org/react";
import { User } from "@/entities/User";
import { capitalize } from "@/utils/base";
import dayjs from "dayjs";
import {
  AssignmentInd,
  BlockSharp,
  CheckCircle,
  CheckCircleOutline,
  Person,
} from "@mui/icons-material";

const UsersPage: NextPage = () => {
  const [users, setUsers] = useState<User[]>([]);
  const { http } = useHttp();

  const getUserList = async (silent = false) => {
    const res = await http.get(
      "/api/user/list",
      {},
      { isOpenLoading: true, silent }
    );
    if (res?.success) {
      setUsers(res.data as User[]);
    }
  };

  const getUserListRef = useRef(getUserList);

  useMounted(() => {
    getUserListRef.current();
  });

  const cols = [
    "id",
    "avatar",
    "name",
    "email",
    "role",
    "createdAt",
    "disabled",
    "operation",
  ];
  const columns = cols.map((col) => ({
    key: col,
    label:
      col == "disabled" ? "Status" : capitalize(col.replace(/[A-Z]/g, " $&")),
  }));

  const getVal = (item: User, key: string | number) => {
    const val =
      key === "avatar"
        ? getKeyValue(item, "avatarData")
        : getKeyValue(item, key);
    if (key === "avatar") {
      return (
        <Image
          isZoomed
          className="w-10 h-10 rounded-full cursor-pointer"
          src={val}
          alt="avatar"
        />
      );
    } else if (key === "role") {
      const roleVal = val == 2 ? "normal" : "admin";
      return (
        <Chip
          size="sm"
          startContent={<AssignmentInd className="text-md" />}
          color={roleVal === "admin" ? "success" : "default"}
          variant="flat"
        >
          {roleVal}
        </Chip>
      );
    } else if (key === "disabled") {
      const statusVal = val ? "disabled" : "active";
      return (
        <Chip
          size="sm"
          startContent={
            statusVal === "disabled" ? (
              <BlockSharp className="text-md" />
            ) : (
              <CheckCircleOutline className="text-md" />
            )
          }
          color={statusVal === "disabled" ? "warning" : "success"}
          variant="flat"
        >
          {statusVal}
        </Chip>
      );
    } else if (key === "createdAt") {
      const day = dayjs(val).format("YYYY-MM-DD HH:mm:ss");
      return day;
    } else {
      return val;
    }
  };

  const handleChangeRole = async (role: number, id: number) => {
    const res = await http.post(
      "/api/user/role",
      { role, id },
      { isOpenLoading: true }
    );
    if (res?.success) {
      getUserListRef.current(true);
    }
  };

  const handleChangeStatus = async (disabled: number, id: number) => {
    const res = await http.post(
      "/api/user/status",
      { disabled, id },
      { isOpenLoading: true }
    );
    if (res?.success) {
      getUserListRef.current(true);
    }
  };

  return (
    <div className="users-page p-6">
      <Table className="text-center" aria-label="users table">
        <TableHeader columns={columns}>
          {(column) => (
            <TableColumn
              className="text-center"
              align="end"
              allowsResizing
              key={column.key}
            >
              {column.label}
            </TableColumn>
          )}
        </TableHeader>
        <TableBody items={users} emptyContent="no data">
          {(item) => (
            <TableRow key={item.id}>
              {(columnKey) =>
                columnKey === "operation" ? (
                  <TableCell>
                    {item.role == 2 ? (
                      <Button
                        variant="flat"
                        className="m-2 rounded-md"
                        size="sm"
                        color="primary"
                        onClick={() => handleChangeRole(1, item.id)}
                      >
                        Be Admin
                      </Button>
                    ) : (
                      <Button
                        variant="flat"
                        className="m-2 rounded-md"
                        size="sm"
                        color="primary"
                        onClick={() => handleChangeRole(2, item.id)}
                      >
                        Be Normal
                      </Button>
                    )}
                    {!item.disabled ? (
                      <Button
                        variant="flat"
                        className="m-2 rounded-md"
                        size="sm"
                        color="danger"
                        onClick={() => handleChangeStatus(1, item.id)}
                      >
                        Disable
                      </Button>
                    ) : (
                      <Button
                        variant="flat"
                        className="m-2 rounded-md"
                        size="sm"
                        color="danger"
                        onClick={() => handleChangeStatus(0, item.id)}
                      >
                        Enable
                      </Button>
                    )}
                  </TableCell>
                ) : (
                  <TableCell>{getVal(item, columnKey)}</TableCell>
                )
              }
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  );
};

export { getServerSideProps };

export default withAuth(UsersPage);
